package com.clouddot.baipai.ui.fragment.H_MainFragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.constraint.ConstraintLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.text.Spanned;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.clouddot.baipai.R;
import com.clouddot.baipai.infrastructure.environment.Env;
import com.clouddot.baipai.model.beam.getArcticById.getArcticByIdResponse;
import com.clouddot.baipai.model.beam.getArcticList.ariticInfo;
import com.clouddot.baipai.model.beam.getArcticList.getArcticListResponse;
import com.clouddot.baipai.ui.activity.H_SMainActivity;
import com.clouddot.baipai.ui.fragment.BaseFragment;
import com.clouddot.baipai.ui.adapter.H_Adapter.newsRecyclerAdapter;
import com.clouddot.baipai.ui.dialog.H_Dialog.H_ContentDailog;
import com.clouddot.baipai.ui.util.recycleView.DivierItemLinear;
import com.clouddot.baipai.ui.util.EscapeUnescapeUtil;
import com.clouddot.baipai.ui.util.SelectedBtnUtil;
import com.clouddot.baipai.ui.util.ThreadPool.ThreadPool;
import com.clouddot.baipai.ui.util.ToastUtil;

import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by wxy on 2018/4/10.
 */

public class H_NewsFragment extends BaseFragment implements View.OnClickListener{

    private View view;
    private Context context;
    private RecyclerView recyclerView;
    private TextView tv1,tv2,tv3;
    private LinearLayout btn1,btn2,btn3;
    private TextView name;
    private LinearLayout constraintLayout1;
    private ConstraintLayout constraintLayout2;
    private LinearLayout last,next;
    private RelativeLayout relativeLayout;
    private int flag = 2;

    private newsRecyclerAdapter classRecyclerAdapter;
    private List<ariticInfo> list   = new ArrayList<>();
    private TextView [] textViews = new TextView[3];
    private LinearLayout[] linearLayouts = new LinearLayout[3];

    private Animation animation;
    private int pageCount;
    private int CurrentPage = 1;
    private String currentBtn = null;

    private Boolean isRunning = false;
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        return view;
    }

    @Override
    protected void setContentView() {
        super.setContentView();

        view = LayoutInflater.from(context).inflate(R.layout.h_f_newsfg,null);
    }

    @Override
    protected void initControls() {
        super.initControls();

        tv1 = view.findViewById(R.id.tv1);
        tv2 = view.findViewById(R.id.tv2);
        tv3 = view.findViewById(R.id.tv3);

        btn1 = view.findViewById(R.id.btn1);
        btn2 = view.findViewById(R.id.btn2);
        btn3 = view.findViewById(R.id.btn3);

        textViews[0] = tv1;
        textViews[1] = tv2;
        textViews[2] = tv3;
        linearLayouts[0] = btn1;
        linearLayouts[1] = btn2;
        linearLayouts[2] = btn3;

        linearLayouts[0].setSelected(true);
        textViews[0].setSelected(true);

        animation = AnimationUtils.loadAnimation(context,R.anim.buttom_click_anim);
        animation.setDuration(200);

        name = view.findViewById(R.id.name);


        recyclerView = view.findViewById(R.id.recycle);
        recyclerView.setLayoutManager(new LinearLayoutManager(context));
        recyclerView.addItemDecoration(new DivierItemLinear(context,DivierItemLinear.VERTICAL_LIST));
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        classRecyclerAdapter = new newsRecyclerAdapter(context,list,flag);
        recyclerView.setAdapter(classRecyclerAdapter);



        constraintLayout1 = view.findViewById(R.id.left);
        constraintLayout2 = view.findViewById(R.id.right);

        constraintLayout1.startAnimation(animation1);
        constraintLayout2.startAnimation(animation2);

        currentBtn = getCodeFromTv(tv1.getText().toString());
        last = view.findViewById(R.id.last);
        next = view.findViewById(R.id.next);

        relativeLayout = view.findViewById(R.id.loading);
        ImageView loading = view.findViewById(R.id.imgloading);
        loading.startAnimation(loadingAnim);
    }

    @Override
    protected void setListener() {
        super.setListener();
        for(int i = 0 ;i < linearLayouts.length ;i++){
            linearLayouts[i].setOnClickListener(this);
            textViews[i].setOnClickListener(this);
        }
        last.setOnClickListener(lastListener);
        next.setOnClickListener(nextListener);
    }

    @Override
    protected void loadParams() {
        super.loadParams();
    }

    @Override
    public void onAttach(Context context) {
        this.context = context;
        super.onAttach(context);
    }

    @Override
    public void onResume() {
        super.onResume();
        if (Env.getAppContext().isInitial)
        {
            flag = 2;
            relativeLayout.setVisibility(View.VISIBLE);
            recyclerView.setVisibility(View.GONE);
            runThreadAction(currentBtn);
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (dailog != null) dailog.closeDialog();
    }

    @Override
    public void onClick(View view) {
        H_SMainActivity.backTime = Env.getAppContext().backMainTime * 60;

        switch (view.getId()){
            case R.id.btn1:
                selectLinear(0);
                flag = 2;
                break;
            case R.id.btn2:
                flag = 3;
                selectLinear(1);
                break;
            case R.id.btn3:
                flag = 4;
                selectLinear(2);
                break;
            case R.id.tv1:
                flag = 2;
                selectLinear(0);
                break;
            case R.id.tv2:
                flag = 3;
                selectLinear(1);
                break;
            case R.id.tv3:
                flag = 4;
                selectLinear(2);
                break;
        }
    }

    @Override
    public void runThreadAction(String actionName) {
        super.runThreadAction(actionName);
    }

    @Override
    protected Object runThreadActionExceute(String actionName) {
        super.runThreadActionExceute(actionName);
        if (actionName.matches("[0-9]+")){
            return Env.getAppPresenter().getArcticById(actionName);
        }else{
            return Env.getAppPresenter().getArcticList(actionName,CurrentPage,Env.getAppContext().itemCount);
        }

    }

    @SuppressLint("HandlerLeak")
    private Handler mhandler = new Handler() {
        @SuppressLint("SetTextI18n")
        @Override
        public void handleMessage(final Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case  2:
                    TextViews.get(2).setText(sp);
                    break;
            }
        }
    };
    private List<TextView> TextViews;
    private Spanned sp;
    private H_ContentDailog dailog;
    private ImageView close;
    @Override
    protected void runThreadActionSuccess(String actionName, Object result) {
        super.runThreadActionSuccess(actionName, result);
        if (actionName.matches("[0-9]+")){
            getArcticByIdResponse response = (getArcticByIdResponse) result;
            if(dailog != null) dailog.closeDialog();
            dailog = new H_ContentDailog(context);
            TextViews = dailog.getTextViews();
            TextViews.get(0).setText(response.BaseData.getTitle());
            TextViews.get(1).setText("发布时间："+response.BaseData.getCreateTimeText());
            TextViews.get(2).setText("正在加载...");
            if(response.BaseData.getDetail() != null && !response.BaseData.getDetail().isEmpty()) {
                final String html = EscapeUnescapeUtil.unescape(response.BaseData.getDetail());
                ThreadPool.getInstance().execute(new Runnable() {
                    @Override
                    public void run() {
                        sp = Html.fromHtml(html, new Html.ImageGetter() {
                            @Override
                            public Drawable getDrawable(String source) {
                                String s = source.contains("http") ? source : Env.getAppContext().IP + source;
                                InputStream is = null;
                                try {
                                    is = (InputStream) new URL(s).getContent();
                                    Drawable d = Drawable.createFromStream(is, null);
                                    d.setBounds(0, 0, d.getIntrinsicWidth(),
                                            d.getIntrinsicHeight());
                                    is.close();
                                    return d;
                                } catch (Exception e) {
                                    e.printStackTrace();
                                    return null;
                                }
                            }
                        }, null);
                        mhandler.sendEmptyMessage(2);
                    }
                });
            }else{
                TextViews.get(2).setText("新闻不支持视频");

            }

            close = dailog.getCloseView();
            close.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    H_SMainActivity.backTime = Env.getAppContext().backMainTime * 60;

                    dailog.closeDialog();
                }
            });
            dailog.showDialog();
        }else {
            relativeLayout.setVisibility(View.GONE);
            getArcticListResponse response = (getArcticListResponse) result;
            if (response.isSuccess()) {
                list.clear();
                if(!response.list.isEmpty()){
                    list = response.list;
                    pageCount = Integer.parseInt(response.PageCount);
                }else {
                    list = new ArrayList<>();
                    ariticInfo infoItem = new ariticInfo();
                    infoItem.setTitle("当前没有数据");
                    infoItem.setCreateTime("");
                    list.add(infoItem);
                }
                classRecyclerAdapter = new newsRecyclerAdapter(context, list,flag);
                recyclerView.setAdapter(classRecyclerAdapter);
                classRecyclerAdapter.setbtnOnclicker(new newsRecyclerAdapter.btnOnclicker() {
                    @Override
                    public void onClicked(int position) {
                        H_SMainActivity.backTime = Env.getAppContext().backMainTime * 60;
                        if (!list.get(position).getTitle().equals("当前没有数据")) {
                            runThreadAction(list.get(position).getId());
                        }
                    }
                });
            } else {
                ToastUtil.showToast(context,response.getErrMsg());
                isRunning = true;
                return;
            }
            recyclerView.setVisibility(View.VISIBLE);
        }
        isRunning = true;

    }

    @Override
    protected void runThreadActionError(String actionName, Exception ex) {
        super.runThreadActionError(actionName, ex);
    }

    private void selectLinear(int i){
        if(isRunning){
            isRunning = false;
            pageCount = 0;
            CurrentPage = 1;
            SelectedBtnUtil.selectedforLinear(linearLayouts,linearLayouts[i]);
            SelectedBtnUtil.selectedforText(textViews,textViews[i]);
            linearLayouts[i].startAnimation(animation);
            textViews[i].startAnimation(animation);
            name.setText(textViews[i].getText());
            relativeLayout.setVisibility(View.VISIBLE);
            recyclerView.setVisibility(View.GONE);
            currentBtn = getCodeFromTv(textViews[i].getText().toString());
            runThreadAction(currentBtn);
        }
    }

    public  String getCodeFromTv(String str){
        if(str.equals(tv1.getText().toString())){
            return "XXXW";
        }else  if(str.equals(tv2.getText().toString())){
            return "TZGG";
        }else  if(str.equals(tv3.getText().toString())){
            return "JJTZ";
        }
        return "";
    }

    private View.OnClickListener lastListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            H_SMainActivity.backTime = Env.getAppContext().backMainTime * 60;

            if (CurrentPage <= 1){
                ToastUtil.showToast(context,"当前是第一页");
                return;
            }
            isRunning = false;
            relativeLayout.setVisibility(View.VISIBLE);
            recyclerView.setVisibility(View.GONE);
            CurrentPage--;
            runThreadAction(currentBtn);
        }
    };

    private View.OnClickListener nextListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            H_SMainActivity.backTime = Env.getAppContext().backMainTime * 60;

            if (CurrentPage >= pageCount){
                ToastUtil.showToast(context,"当前是最后一页");
                return;
            }
            isRunning = false;
            relativeLayout.setVisibility(View.VISIBLE);
            recyclerView.setVisibility(View.GONE);
            CurrentPage++;
            runThreadAction(currentBtn);
        }
    };

}
